package designPattern.Singleton;

//最简单的
class SingletonSimple {
    private static SingletonSimple instance = new SingletonSimple();
    private SingletonSimple (){}
    public static SingletonSimple getInstance() {
        return instance;
    }
}

//不仅能避免多线程同步问题，而且还自动支持序列化机制，防止反序列化重新创建新的对象，绝对防止多次实例化。
enum SingletonEnum {
    INSTANCE;
    public void whateverMethod() {
    }
}

//懒汉式，线程不安全
class SingletonLazy1 {
    private static SingletonLazy1 instance;
    private SingletonLazy1 (){}  //让构造函数为 private，这样该类就不会被实例化

    public static SingletonLazy1 getInstance() {
        if (instance == null) {
            instance = new SingletonLazy1();
        }
        return instance;
    }
}
//懒汉式，线程安全
class SingletonLazy2 {
    private static SingletonLazy2 instance;
    private SingletonLazy2 (){}
    public static synchronized SingletonLazy2 getInstance() {
        if (instance == null) {
            instance = new SingletonLazy2();
        }
        return instance;
    }
}

//双重校验锁，SingletonLazy2的优化
class SingletonDoubleLock {
    private volatile static SingletonDoubleLock singleton; //volatile防止有些大对象没有初始化完成
    private SingletonDoubleLock (){}
    public static SingletonDoubleLock getSingleton() {
        if (singleton == null) {
            synchronized (SingletonDoubleLock.class) { //只有初始化时才需要同步，同步只执行一次
                if (singleton == null) {
                    singleton = new SingletonDoubleLock();
                }
            }
        }
        return singleton;
    }
}

class SingletonInnerClass {
    private static class SingletonHolder {
        private static final SingletonInnerClass INSTANCE = new SingletonInnerClass();
    }
    private SingletonInnerClass (){}
    public static final SingletonInnerClass getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
